const { JSDOM } = require('jsdom')
const fs = require('fs')
const express = require('express')
const { resolve, dirname } = require('path')
const app = express()
const port = 3000


const root = new JSDOM(`
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jsdom</title>
</head>

<body>
    <h1> node 环境通过 jsdom 操作 dom 和 bom </h1>
    <div id="app"></div>
</body>

</html>
`)
const window = root.window
const document = window.document
const fn = () => {
    return new Promise(async (resolve, reject) => {
        const res = await fetch('https://api.thecatapi.com/v1/images/search?limit=10&page=1')
        const data = await res.json()
        const app = document.getElementById('app')
        data.forEach(item => {
            creatImg(item, app)
        })
        fs.writeFile('./index.html', root.serialize(), (data, err) => {
        })
        resolve()
    })

}
const creatImg = (data, app) => {
    const img = document.createElement('img')
    img.src = data.url
    img.style.width = `${data.width}px`
    img.style.height = `${data.height}px`
    app.appendChild(img)
}
app.get('/gethtml', async (req, res) => {
    await fn()
    res.send(fs.readFileSync(resolve(__dirname, './index.html')).toString())
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
